using AutoMapper;
using MediatR;
using SqlSugar;
using TaskProject.Application.Command.Plan;
using TaskProject.Domain.Plan;
using TaskProject.ErrorCode;
using TaskProject.Extension.Plan;
using TaskProject.InfrasIntructure.Implement;

namespace TaskProject.Application.Handler.Plan
{
    /// <summary>
    /// 获取生产计划详情处理器
    /// </summary>
    public class GetProductionPlanDetailHandler : IRequestHandler<GetProductionPlanDetailCommand, APIResult<ProductionPlanDetailDTO>>
    {
        private readonly DatabaseContext _db;
        private readonly IMapper _mapper;

        public GetProductionPlanDetailHandler(DatabaseContext db, IMapper mapper)
        {
            _db = db;
            _mapper = mapper;
        }

        public async Task<APIResult<ProductionPlanDetailDTO>> Handle(GetProductionPlanDetailCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<ProductionPlanDetailDTO>();

            try
            {
                // 获取生产计划主表信息
                var productionPlan = await _db.sqlSugar.Queryable<ProductionPlanModel>()
                    .Where(p => p.PlanId == request.PlanId && !p.IsDel)
                    .FirstAsync(cancellationToken);

                if (productionPlan == null)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "生产计划不存在";
                    return result;
                }

                // 获取生产物品列表
                var productionItems = await _db.sqlSugar.Queryable<ProductionPlanItemModel>()
                    .Where(i => i.PlanId == request.PlanId)
                    .OrderBy(i => i.SortOrder)
                    .ToListAsync(cancellationToken);

                // 获取附件列表
                var attachments = await _db.sqlSugar.Queryable<ProductionPlanAttachmentModel>()
                    .Where(a => a.PlanId == request.PlanId)
                    .ToListAsync(cancellationToken);

                // 构建详情DTO
                var detailDTO = new ProductionPlanDetailDTO
                {
                    PlanId = productionPlan.PlanId,
                    PlanSubject = productionPlan.PlanSubject,
                    PlanOrderNumber = productionPlan.PlanOrderNumber,
                    DocumentDate = productionPlan.DocumentDate,
                    Remarks = productionPlan.Remarks,
                    SalesOrderNumber = productionPlan.SalesOrderNumber,
                    RelatedProjectName = productionPlan.RelatedProjectName,
                    PlanStatus = productionPlan.PlanStatus,
                    PlanStatusName = GetPlanStatusName(productionPlan.PlanStatus),
                    ExpectedStartDate = productionPlan.ExpectedStartDate,
                    ExpectedEndDate = productionPlan.ExpectedEndDate,
                    ProductionLine = productionPlan.ProductionLine,
                    Priority = productionPlan.Priority,
                    PriorityName = GetPriorityName(productionPlan.Priority),
                    CreateName = productionPlan.CreateName,
                    CreateDate = productionPlan.CreateDate,
                    UpdateName = productionPlan.UpdateName,
                    UpdateDate = productionPlan.UpdateDate,
                    ProductionItems = _mapper.Map<List<ProductionPlanItemDTO>>(productionItems),
                    Attachments = _mapper.Map<List<ProductionPlanAttachmentDTO>>(attachments)
                };

                result.Code = APIEnum.Success;
                result.Msg = "获取成功";
                result.Data = detailDTO;
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.Fail;
                result.Msg = $"获取失败：{ex.Message}";
            }

            return result;
        }

        /// <summary>
        /// 获取计划状态名称
        /// </summary>
        private string GetPlanStatusName(int status)
        {
            return status switch
            {
                0 => "草稿",
                1 => "已确认",
                2 => "执行中",
                3 => "已完成",
                4 => "已取消",
                _ => "未知状态"
            };
        }

        /// <summary>
        /// 获取优先级名称
        /// </summary>
        private string GetPriorityName(int priority)
        {
            return priority switch
            {
                1 => "低",
                2 => "中",
                3 => "高",
                4 => "紧急",
                _ => "未知优先级"
            };
        }
    }
} 